﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NLog;
using Topshelf;
using System.Configuration;

namespace SYT.Common.ServiceFactory
{
    public class WinServiceFactory
    {
        private readonly Logger _loger;
        private readonly BaseWinServer _baseWinServer;
        public WinServiceFactory(Logger loger, BaseWinServer baseWinServer)
        {
            _loger = loger;
            _baseWinServer = baseWinServer;
        }

        public void Build()
        {
            string serviceDescription=ConfigurationManager.AppSettings["ServiceDescription"];
            string serviceDisplayName = ConfigurationManager.AppSettings["ServiceDisplayName"];
            string serviceName = ConfigurationManager.AppSettings["ServiceName"];
            HostFactory.Run(x =>
            {
                x.RunAsLocalSystem();
                x.SetDescription(serviceDescription);
                x.SetDisplayName(serviceDisplayName);
                x.SetServiceName(serviceName);
                x.Service(factory => CreateServer());
            });
        }

        public BaseWinServer CreateServer()
        {
            try
            {
                _baseWinServer.Initialize();
                return _baseWinServer;
            }
            catch (Exception ex)
            {
                _loger.Error(ex.StackTrace + Environment.NewLine + ex.Message);
            }
            return null;
        }
    }
}
